package com.bjlytr.license.client.intercetor;

import com.bjlytr.license.client.core.LicenseVerify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Ledison
 * @date 2021/9/16
 */
@Slf4j
@Component("licenseCheckInterceptor")
public class LicenseCheckInterceptor extends HandlerInterceptorAdapter {

    // 计数
    private AtomicInteger count = new AtomicInteger(0);
    // 请求阈值
    private Integer verifyThreshold = 500;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        count.incrementAndGet();
        LicenseVerify licenseVerify = new LicenseVerify();
        if (count.get() > verifyThreshold) {
            boolean verifyResult = licenseVerify.verify();
            // 校验证书是否有效
            count.set(0);
            if (verifyResult) {
                return true;
            } else {
                throw new RuntimeException("您的证书无效，请核查服务器是否取得授权或重新申请证书！");
            }

        }
        return true;
    }
}
